using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Comteck.Winforms.Utils {

  /// <summary>
  /// DataTable转化帮助类
  /// </summary>
  public class DataTableConvertHelper {

    /// <summary>
    /// ListDictionary转DataTable
    /// </summary>
    /// <param name="list">List<Dictionary<string, object>>对象</param>
    /// <returns>DataTable对象</returns>
    public static DataTable ListDictionaryToDataTable(List<Dictionary<string, object>> list) {
      // 创建一个新的 DataTable 对象
      DataTable dataTable = new DataTable();

      // 如果列表为空，则直接返回空表
      if (list.Count == 0) return dataTable;

      // 获取第一个字典的所有键作为列名
      var keys = list[0].Keys;
      foreach (var key in keys) {
        // 获取类型
        JObject jObject = (JObject)list[0][key];
        var typeString = (string)jObject["Type"];
        var columnType = Type.GetType(typeString);

        // 添加列到 DataTable
        dataTable.Columns.Add(key, columnType);
      }

      // 遍历列表中的每个字典
      foreach (var dict in list) {
        // 创建一个新的 DataRow
        DataRow row = dataTable.NewRow();

        // 使用字典的键值对填充 DataRow
        foreach (var key in keys) {
          JObject jObject = (JObject)dict[key];
          var value = jObject["Value"];

          if (value.ToObject<object>() != null) {
            row[key] = value.ToObject<object>();
          } else {
            row[key] = DBNull.Value;
          }
        }

        // 将填充好的 DataRow 添加到 DataTable
        dataTable.Rows.Add(row);
      }

      return dataTable;
    }
  }
}
